package com.erlinyou.im.web.controller.chat;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;

import org.aspectj.bridge.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.erlinyou.im.common.util.StringUtil;
import com.erlinyou.im.common.uuid.UUIDGenerator;
import com.erlinyou.im.model.chat.ChatMessage;
import com.erlinyou.im.model.chat.ChatMessageDel;
import com.erlinyou.im.model.chat.ChatSession;
import com.erlinyou.im.model.goodfirend.Goodfirend;
import com.erlinyou.im.model.group.Group;
import com.erlinyou.im.model.group.Groupmembers;
import com.erlinyou.im.model.groupmove.Ofcallcenter;
import com.erlinyou.im.model.groupmove.Ofcallcenteraffiliation;
import com.erlinyou.im.model.groupmove.Ofcontacts;
import com.erlinyou.im.model.groupmove.Ofhistorymessagedel;
import com.erlinyou.im.model.groupmove.Ofmucroom;
import com.erlinyou.im.model.ofroster.Ofroster;
import com.erlinyou.im.service.chat.IChatMessageDelService;
import com.erlinyou.im.service.chat.IChatMessageService;
import com.erlinyou.im.service.chat.IChatSessionService;
import com.erlinyou.im.service.goodfirend.GoodfirendService;
import com.erlinyou.im.service.group.GroupService;
import com.erlinyou.im.service.group.IGroupMemService;
import com.erlinyou.im.service.groupmove.OfcallcenterService;
import com.erlinyou.im.service.groupmove.OfcallcenteraffiliationServcie;
import com.erlinyou.im.service.groupmove.OfcontactsService;
import com.erlinyou.im.service.groupmove.OfhistorymessageService;
import com.erlinyou.im.service.groupmove.OfhistorymessagedelService;
import com.erlinyou.im.service.groupmove.OfmucmemberService;
import com.erlinyou.im.service.groupmove.OfmucroomService;
import com.erlinyou.im.service.ofroster.OfrosterService;
import com.erlinyou.im.web.controller.base.ResultCode;
import com.erlinyou.im.web.controller.base.ResultJson;
import com.erlinyou.im.web.controller.base.ResultJsonBuild;
import com.erlinyou.im.web.controller.base.message.ChatType;
import com.erlinyou.im.web.controller.base.message.MessageType;
import com.erlinyou.travel.model.user.TUser;
import com.erlinyou.travel.service.user.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;

@Api(tags = { "Move" })
@Controller
@RequestMapping(value = "/move")
@Deprecated
public class DbMoveController {
	private static Logger logger = LoggerFactory.getLogger(ChatMessageController.class);
	@Resource
	private OfrosterService ofrosterService;
	
	@Resource
	private OfcontactsService ofcontactsService;
	
	@Resource
	private GoodfirendService goodfirendService;
	
	@Resource
	private OfmucroomService ofmucroomService;
	
	@Resource
	private OfmucmemberService ofmucmemberService;
	
	@Resource
	private IChatSessionService chatSessionService;
	
	@Resource
	private IGroupMemService groupMemService;
	
	@Resource
	private GroupService groupservice;
	
	@Resource
	private IUserService userService;
	
	@Resource
	private IChatMessageService chatMessageService;
	
	@Resource
	private OfhistorymessageService ofhistorymessageService;
	
	@Resource
	private OfhistorymessagedelService ofhistorymessagedelService;
	
	@Resource
	private IChatMessageDelService chatMessageDelService;
	
	@Resource
	private OfcallcenterService ofcallcenterService;
	
	@Resource
	private OfcallcenteraffiliationServcie ofcallcenteraffiliationService;
	
	@ApiOperation(value = "好友表迁移", notes = "好友表迁移测试")
	@PostMapping(value = "/rosterMove")
	@ResponseBody
	public ResultJson<Object> RosterMove() {
	//	boolean b = false;
		ResultJsonBuild<Object> resultJsonBuild = new ResultJsonBuild<Object>();
		List<Ofroster> list = ofrosterService.findBySub((byte)3);
		System.out.println("list 长度 -》"+list.size());
		boolean b = false;
			ArrayList<Goodfirend> goodfirendList = new ArrayList<Goodfirend>();
			for (Ofroster ofroster : list) {
				Goodfirend goodfirend = new Goodfirend();
				long createtime = System.currentTimeMillis();
				long jid = 0;
				long userid = 0;
				try {
					jid = Long.valueOf(ofroster.getJid().split("@")[0]);
					userid = Long.valueOf(ofroster.getUsername());
				} catch (NumberFormatException e) {
					continue;
				}
				
				if(jid<1||userid<1) {
					continue;
				}
				goodfirend.setCreatetime(createtime);
				goodfirend.setNoreadnum(0);
				goodfirend.setJid(jid);
				goodfirend.setRelation(3);
				goodfirend.setUserid(userid);
				goodfirend.setFpermission("default");
				goodfirend.setPermission("default");
				goodfirendList.add(goodfirend);
			}
			b = goodfirendService.saveAll(goodfirendList)!=null;
			JSONObject jsonObject = new JSONObject();
			jsonObject.accumulate("msg", "保存条数:"+list.size());
		return b?resultJsonBuild.success(jsonObject):resultJsonBuild.error(ResultCode.UNKONW_ERROR.getCode(), "保存失败");
	}
	@ApiOperation(value = "group表迁移", notes = "group迁移测试")
	@ApiImplicitParams({ @ApiImplicitParam(name = "startPage", required = true, value = "开始条数", dataType="int",example="0", paramType = "query"),
		@ApiImplicitParam(name = "rows", required = true, value = "条数", dataType="int",example="0", paramType = "query")})
	@PostMapping(value = "/groupMove")
	@ResponseBody
	public ResultJson<Object> groupMove(@RequestParam(required = true) int startPage,
			@RequestParam(required = true) int rows) throws Exception {
		List<Map<String,Object>> list = ofmucroomService.seleRoomId(startPage, rows);
		ChatMessageController controller = new ChatMessageController();
		List<Group> grouplist = new ArrayList<Group>();
		for (Map<String, Object> map : list) {
			Group group = new Group();
			Integer roomID = 0;
			Long creationDate = 0L;
			String naturalName = null;
			try {
				roomID = Integer.valueOf(map.get("roomID").toString());
				creationDate = Long.valueOf(map.get("creationDate").toString());
				naturalName = map.get("naturalName").toString();
			} catch (Exception e) {
				logger.warn("groupMove error:roomID->"+roomID);
			}
			long jid = 0;
			try {
				if(!StringUtil.isEmpty((String)map.get("jid"))) {
					jid = Long.valueOf(map.get("jid").toString().split("@")[0]).longValue();
					Groupmembers groupmembers = new Groupmembers();
					groupmembers.setCt(creationDate);
					groupmembers.setGroupid(roomID);
					groupmembers.setUserid(jid);
					TUser user = userService.findByUserid(jid);
					String nickName;
					try {
						nickName = user.getNickName();
					} catch (Exception e) {
						nickName = "";
					}
					groupmembers.setUserName(nickName);
					groupmembers.setIsNotice(0);
					groupmembers.setGtype(1);
					groupMemService.save(groupmembers);
				}
			} catch (Exception e) {
				logger.warn("groupMove error:roomID->"+roomID);
			}
			group.setCt(creationDate);
			group.setGtype(1);
			group.setName(naturalName);
			group.setOwner(jid);
			group.setId(roomID);
			group.setUid(UUIDGenerator.nextId());
			
			List<String> urlPath = new ArrayList<String>();
			
			if(group.getId()==143) {
				System.out.println("--"); 
			}
			List<Map<String,Object>> ofmucmemberlist = ofmucmemberService.seleId(Long.valueOf(roomID.toString()));
			if(ofmucmemberlist.size()==0) {
				continue;
			}else{
				if(group.getOwner()==0) {
					group.setOwner(Long.valueOf(ofmucmemberlist.get(0).get("jid").toString().split("@")[0]));
				}
			}
			for (Map<String,Object> memMap : ofmucmemberlist) {
				Groupmembers groupmembers = new Groupmembers();
				Long jid1 = null;
				String nickname = null;
				Long createTime = null;
				try {
					jid1 = Long.valueOf(memMap.get("jid").toString().split("@")[0]);
					nickname = memMap.get("nickname").toString();
					createTime = Long.valueOf(memMap.get("createTime").toString());
				} catch (Exception e) {
					logger.warn("groupMove error:roomID->"+roomID);
				}
				if(nickname == null||jid1 == null) {
					continue;
				}
				if(createTime==null) {
					createTime=System.currentTimeMillis();
				}
				groupmembers.setCt(createTime);
				groupmembers.setGroupid(roomID);
				groupmembers.setUserid(jid1);
				groupmembers.setUserName(nickname);
				groupmembers.setIsNotice(0);
				groupmembers.setGtype(1);
				boolean b = groupMemService.save(groupmembers)!=null;
				if(!b) {
					throw new RuntimeException();
				}
				TUser tuser = userService.findByUserid(groupmembers.getUserid());
				
				if(tuser.getImage()==null) {
					continue;
				}
				
				if(group.getOwner()==tuser.getUserid()) {
					urlPath.add(tuser.getImage());
				}
				
				if(urlPath.size()<5 && group.getOwner()!=tuser.getUserid()) {
					urlPath.add(tuser.getImage());
				}
			}
			
			String image = controller.toImg(group.getUid(), group.getOwner(), urlPath);
			
			if(StringUtil.isEmpty(image)) {
				throw new RuntimeException();
			}
			group.setImage(image);
			grouplist.add(group);
		}
		
		boolean saveAndMove = groupservice.saveAll(grouplist).size()>0;
		ResultJsonBuild<Object> resultJsonBuild = new ResultJsonBuild<Object>();
		if(saveAndMove) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.accumulate("msg", "groupmove迁移成功:grouplist->"+grouplist.size());
			return resultJsonBuild.success(jsonObject);
		}
		return resultJsonBuild.error(99, "不知道啥错");
	}
	
	@ApiOperation(value = "消息表迁移", notes = "聊天消息表迁移测试")
	@ApiImplicitParams({ @ApiImplicitParam(name = "startPage", required = true, value = "开始条数", dataType="int",example="0", paramType = "query"),
		@ApiImplicitParam(name = "rows", required = true, value = "结束条数", dataType="int",example="0", paramType = "query")})
	@PostMapping(value = "/messageMove")
	@ResponseBody
	public boolean messageMove(@RequestParam(required = true) int startPage,
			@RequestParam(required = true) int rows) {
		List<Map<String,Object>> ofhMsglist = ofhistorymessageService.selectAll(startPage,rows);
		List<ChatMessage> messagelist = new ArrayList<ChatMessage>();
		if(ofhMsglist.size()<1) {
			return false;
		}
		for (Map<String, Object> map : ofhMsglist) {
			ChatMessage message = new ChatMessage();
			try {
				Long hmfrom = null;
				Long hmto = null;
				String hmmsgid = null;
				Long hmcreatetime = null;
				String hmgid = null;
				String hmcontentblob = null;
				String hmclientmsgid = null;
				String properties = null;
				String hmtype = null;
				Long visitorId = null;
				try {
					hmmsgid = map.get("hmmsgid").toString();
	//				hmfrom = Long.valueOf(map.get("hmfrom").toString().split("/")[1].split("@")[0]);
					hmfrom = Long.valueOf(map.get("hmfrom").toString().split("@")[0]);
					hmto = Long.valueOf(map.get("hmto").toString().split("@")[0]);
		//群聊使用	
		//			String hmto1 = map.get("hmto").toString().split("@")[0];
		//			Map<String,Object>  findByName = ofmucroomService.findByName(hmto1);
		//			hmto = Long.valueOf(findByName.get("roomID").toString());
		/*			if("boobuzteam".equals(hmto1)) {//boobuzteam   expedia    viator    ecab
						hmto = 1L;
					}else if("expedia".equals(hmto1)) {
						hmto = 2L;
					}else if("viator".equals(hmto1)) {
						hmto = 3L;
					}else if("ecab".equals(hmto1)) {
						hmto = 4L;
					}else{
						throw new RuntimeException();
					}
					if(map.get("hmto").toString().contains("/")) {
						visitorId = Long.valueOf(map.get("hmto").toString().split("/")[1].split("@")[0]);
					}*/
					hmcreatetime = Long.valueOf(map.get("hmcreatetime").toString());
					hmgid = map.get("hmgid").toString();
					hmcontentblob = map.get("hmcontentblob").toString();
					properties = map.get("properties").toString();
					hmclientmsgid = map.get("hmclientmsgid").toString();
					hmtype = map.get("hmtype").toString();
				} catch (Exception e) {
						logger.warn("groupMove error:msgid->"+hmmsgid);
						logger.warn("error->"+e);
						continue;
				}
				message.setClientid(hmclientmsgid);
				message.setCt(hmcreatetime);
				message.setFromId(hmfrom);
				message.setToId(hmto);
				//单聊使用
				message.setGid(getGid(message.getFromId(),message.getToId()));
				//群聊使用
				message.setGid(message.getToId()+"");
				message.setId(hmmsgid);
				message.setRev(0);
				message.setVisitorId(visitorId);
				if(hmtype.equals("chat")) {
					message.setCtype(ChatType.SINGLE.getCode());
				}else if(hmtype.equals("groupchat")) {
					message.setCtype(ChatType.GROUP.getCode());
				}else if(hmtype.equals("callcenterchat")){
					message.setCtype(ChatType.CALLCENTER.getCode());
				}else if(hmtype.equals("media")) {
					if(message.getGid().contains("_")) {
						message.setCtype(ChatType.SINGLE.getCode());
					}else{
						if(hmgid.indexOf("callcenter")==0){
							message.setCtype(ChatType.CALLCENTER.getCode());
						}else {
							message.setCtype(ChatType.GROUP.getCode());
						}
					};
				}else {
					throw new RuntimeException();
				}
				message.setContent(hmcontentblob);
				if(isJson(properties)) {
					JSONObject jsonObject = JSONObject.fromObject(properties);
					if(jsonObject.containsKey("msgType")) {
						String msgType = jsonObject.get("msgType").toString();
						switch (msgType) {
						
						case "msg_type_text":
							message.setType(1);
							break;
						case "msg_type_img":
							message.setType(2);
							break;
						case "msg_type_video":
							message.setType(3);
							break;
						case "msg_type_voice":
							message.setType(4);
							break;
						case "msg_type_file":
							message.setType(5);
							break;
						case "msg_type_share_poi":
							message.setType(8);
							break;
						case "msg_type_list":
							message.setType(9);
							break;
						case "msg_type_share_app":
							message.setType(10);
							break;
						case "msg_type_location":
							message.setType(12);
							break;
						default:
							message.setType(13);
							break;
						}
					}else {
						message.setType(MessageType.CONTENT.getCode());
					}
				}else {
					message.setType(MessageType.CONTENT.getCode());
				}
			} catch (NumberFormatException e) {
				logger.warn("groupMove error:msgid->"+message.getId());
				continue;
			}
			
			boolean equals = message.getClientid().equals("0_0_1561255420010514");
			boolean equals1 = message.getClientid().equals("RHOCi-2608741705330");
			if(equals||equals1) {continue;}
			messagelist.add(message);
		}
		boolean b = chatMessageService.saveAll(messagelist)!=null;
		
		return b;
	}
	
	
	@ApiOperation(value = "消息表单聊gid修改", notes = "消息表单聊gid修改")
	@ApiImplicitParams({ @ApiImplicitParam(name = "startPage", required = true, value = "开始条数", dataType="int",example="0", paramType = "query"),
		@ApiImplicitParam(name = "rows", required = true, value = "结束条数", dataType="int",example="0", paramType = "query")})
	@PostMapping(value = "/messageUpdate")
	@ResponseBody
	public boolean messageUpdate(@RequestParam(required = true) int startPage,
			@RequestParam(required = true) int rows) {
		List<ChatMessage> list = chatMessageService.findByCtype(1);
		for (ChatMessage chatMessage : list) {
			boolean contains = chatMessage.getGid().contains("_");
			if(!contains) {
				Long fromId = chatMessage.getFromId();
				Long toId = chatMessage.getToId();
				String gid = getGid(fromId,toId);
				chatMessage.setGid(gid);
				boolean b = chatMessageService.save(chatMessage)!=null;
				if(!b) {
					throw new RuntimeException();
				}
			}
		}
		
		return true;
	}

	
	public static boolean isJson(String content) {
        try {
            JSONObject.fromObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
	
	@ApiOperation(value = "删除表迁移", notes = "删除表迁移测试")
	@PostMapping(value = "/delMsgMove")
	@ResponseBody
	public boolean delMsgMove() {
		boolean b = false;
		List<Ofhistorymessagedel> OfhistorymessagedelfindAll = ofhistorymessagedelService.findAll();
		int num = 26215;
		if(OfhistorymessagedelfindAll.size()==num) {
			List<ChatMessageDel> ChatMessageDelfindAll = new ArrayList<ChatMessageDel>();
			for (Ofhistorymessagedel ofhistorymessagedel : OfhistorymessagedelfindAll) {
				ChatMessageDel chatMessageDel = new ChatMessageDel();
				chatMessageDel.setCt(ofhistorymessagedel.getHmdcreatetime()); 
				chatMessageDel.setUserid(Long.valueOf(ofhistorymessagedel.getHmdelid().split("@")[0]));
				chatMessageDel.setXid(ofhistorymessagedel.getHmid());
				ChatMessageDelfindAll.add(chatMessageDel);
			}
			b = chatMessageDelService.saveAll(ChatMessageDelfindAll)!=null;
		}
		return b;
	}
	@ApiOperation(value = "群成员表username字段修改为昵称", notes = "群成员表username字段修改为昵称")
	@PostMapping(value = "/groupMemUpdateUsername")
	@ResponseBody
	public ResultJson<Object> groupMemUpdateUsername() {
		
		List<Groupmembers> findAll = groupMemService.findAll();
		for (Groupmembers groupmembers : findAll) {
			boolean b = false;
			Long userid = groupmembers.getUserid();
			TUser findByUserid = userService.findByUserid(userid);
			groupmembers.setUserName(findByUserid.getNickName());
			b = groupMemService.save(groupmembers)!=null;
			if(!b) {
				return ResultJsonBuild.buildObj(ResultCode.UNKONW_ERROR);
			}
		}
		
		return ResultJsonBuild.buildObj(ResultCode.SUCCESS);
		
	}
	@ApiOperation(value = "Callcenter数据迁移", notes = "Callcenter数据迁移")
	@PostMapping(value = "/callcenterMove")
	@ResponseBody
	public ResultJson<Object> callcenterMove() {
		List<Ofcallcenter> ofcallcenterAll = ofcallcenterService.findAll();
		for (Ofcallcenter ofcallcenter : ofcallcenterAll) {
			Group group = new Group();
			if((int)ofcallcenter.getCallcenterType()!=2) {
				continue;
			}
			Optional<Ofcallcenteraffiliation> findById = ofcallcenteraffiliationService.findById((long)ofcallcenter.getCallcenterID());
			Ofcallcenteraffiliation ofcallcenteraffiliation = null;
			if(findById.isPresent()) {
				ofcallcenteraffiliation = findById.get();
			}
			String poiId = null;
			String imgurl = null;
			try {
				poiId = ofcallcenter.getPoiId();
				imgurl = ofcallcenter.getImgurl();
			} catch (Exception e) {
			}
			group.setGtype(3);
			group.setCt(1564047579843L);
			group.setImage(imgurl);
			group.setName(ofcallcenter.getNaturalName());
			String owner = null;
			if(ofcallcenteraffiliation.getJid().toString().contains("@")) {
				owner = ofcallcenteraffiliation.getJid().toString().split("@")[0];
			}else {
				owner = ofcallcenteraffiliation.getJid().toString();
			}
			group.setOwner(Long.valueOf(owner));
			group.setPoiId(poiId);
			group.setUid(UUIDGenerator.nextId());
			Group save = groupservice.save(group);
			if(save==null) {
				return ResultJsonBuild.buildObj(ResultCode.UNKONW_ERROR);
			}
			Groupmembers groupmembers = new Groupmembers();
			groupmembers.setCt(save.getCt());
			groupmembers.setGroupid(save.getId());
			groupmembers.setGtype(save.getGtype());
			groupmembers.setIsNotice(0);
			groupmembers.setUserid(save.getOwner());
			Optional<TUser> findById2 = userService.findById(save.getOwner());
			TUser tUser = null;
			if(findById2.isPresent()) {
				tUser = findById2.get();
			}
			if(tUser!=null) {
				groupmembers.setUserName(tUser.getNickName());
			}
			Groupmembers save2 = groupMemService.save(groupmembers);
			if(save2==null) {
				return ResultJsonBuild.buildObj(ResultCode.UNKONW_ERROR);
			}
			
			List<Map<String,Object>> map = ofcallcenteraffiliationService.seleMember((long)ofcallcenter.getCallcenterID());
			for (Map<String,Object> map1 : map) {
				String jid = map1.get("jid").toString().split("@")[0];
				Groupmembers groupmembers1 = new Groupmembers();
				groupmembers1.setCt(save.getCt());
				groupmembers1.setGroupid(save.getId());
				groupmembers1.setGtype(save.getGtype());
				groupmembers1.setIsNotice(0);
				Optional<TUser> findById21 = userService.findById(Long.valueOf(jid));
				TUser tUser1 = null;
				if(findById21.isPresent()) {
					tUser1 = findById21.get();
				}
				if(tUser1!=null) {
					groupmembers1.setUserName(tUser1.getNickName());
					groupmembers1.setUserid(tUser1.getUserid());
				}
				Groupmembers save21 = groupMemService.save(groupmembers1);
				if(save21==null) {
					return ResultJsonBuild.buildObj(ResultCode.UNKONW_ERROR);
				}
				}
			}
			return ResultJsonBuild.buildObj(ResultCode.SUCCESS);
		}
		
		@ApiOperation(value = "contacts数据迁移", notes = "contacts数据迁移")
		@PostMapping(value = "/contactsMove")
		@ResponseBody
		public ResultJson<Object> contactsMove() {
			
			List<Ofcontacts> findAll = ofcontactsService.findAll();
			for (Ofcontacts ofcontacts : findAll) {
				Long userid;
				try {
					userid = Long.valueOf(ofcontacts.getCid().split("@")[0]);
				} catch (NumberFormatException e) {
					continue;
				}
				Long uptime = ofcontacts.getCuptime();
	//			String croomname = ofcontacts.getCroomname();
				String clastmsg = ofcontacts.getClastmsg();
				String type = ofcontacts.getCtype();
				int ctype = 0;
				ChatSession entity = new ChatSession();
				if("chat".equals(type)) {
					Long rid = 0L;
					try {
						rid = Long.valueOf(ofcontacts.getCrid().split("@")[0]);
					} catch (NumberFormatException e) {
						continue;
					}
					ctype = 1;
					entity.setRid(rid);
				}else if("groupchat".equals(type)) {
					Long groupid = Long.valueOf(ofcontacts.getCroomid());
					ctype = 2;
					entity.setRid(groupid);
				}else if("callcenterchat".equals(type)) {
					Long groupid = Long.valueOf(ofcontacts.getCroomid());
					ctype = 3;
					entity.setRid(groupid);
				}else {continue;}
				
				ChatMessage chatMessage = null;
				if(ctype==1) {
					chatMessage = chatMessageService.findByfromIdAndtoId(userid,getGid(userid,entity.getRid()), ctype);
				}else if(ctype==2) {
					chatMessage = chatMessageService.findByfromIdAndtoId(userid,entity.getRid()+"", ctype);
				}else {
					chatMessage = chatMessageService.findByfromIdAndtoId(userid,entity.getRid()+"", ctype);
				}
				JSONObject jsonObject = new JSONObject();
				if(chatMessage!=null) {
					jsonObject.accumulate("id", chatMessage.getId());
					jsonObject.accumulate("fromId", chatMessage.getFromId());
					jsonObject.accumulate("toId", chatMessage.getToId());
					jsonObject.accumulate("type", chatMessage.getType());
					jsonObject.accumulate("ctype", chatMessage.getCtype());
					jsonObject.accumulate("content", chatMessage.getContent());
					jsonObject.accumulate("ct", chatMessage.getCt());
					jsonObject.accumulate("clientid", chatMessage.getClientid());
					jsonObject.accumulate("rev", chatMessage.getRev());
					jsonObject.accumulate("off", 0);
					TUser user = userService.findByUserid(chatMessage.getToId());
					try {
						jsonObject.accumulate("image", user.getImage());
					} catch (Exception e) {
						jsonObject.accumulate("image", "");
					}
					try {
						jsonObject.accumulate("nickName", user.getNickName());
					} catch (Exception e) {
						jsonObject.accumulate("nickName", "");
					}
					entity.setContent(jsonObject.toString());
				}else {
					entity.setContent("");
				}
				entity.setUserid(userid);
				entity.setUptime(uptime);
				entity.setNoreadnum(0);
				entity.setCtype(ctype);
				if(entity.getRid()==0) {
					continue;
				}
				chatSessionService.save(entity);
			}
		
			return ResultJsonBuild.buildObj(ResultCode.SUCCESS);
			
		
		}
	/*Eric聊天记录导出
	@ApiOperation(value = "poiTxt", notes = "poiTxt")
	@PostMapping(value = "/poiOut")
	@ResponseBody
	public ResultJson<Object> poiOut() throws IOException {
		
		List<Map<String,Object>> list = ofhistorymessageService.selectAllByEric();
		System.out.println(list.size());
		BufferedWriter out = null;
		for (Map<String, Object> map : list) {
			long longValue = Long.valueOf(map.get("hmcreatetime").toString()).longValue();
			SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a E");
			String format = sdf3.format(new Date(longValue));
			String content = map.get("hmcontentblob").toString();
			try {
				out = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream("D:\\upload\\UI_bug_management_26.txt", true)));
				out.write("时间->"+format+"\t");
				out.write("文本消息->"+content+"\r\n");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				out.close();
			}
		}
		
		return ResultJsonBuild.buildObj(ResultCode.SUCCESS);
		
	}*/
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	private String getGid(long from, long to) {
		return from > to ? from + "_" + to : to + "_" + from;
	}
	
	
}
